<template>
  <div>
    <el-popover
      v-model="popperShow"
      :append-to-body="appendToBody"
      placement="top"
      popper-class="time-all-select-style"
      trigger="click"
      @show="show">
      <div class="filter-list">
        <div class="top-container">
          <div><Title :title="title" /></div>
          <div v-if="mode !== 'single'" class="top-btn flex">
            <div class="flex flex-center">
              <el-checkbox v-model="saveFilter">
                <span :style="{fontWeight: saveFilter ? 'bold' : ''}" style="color: #333;">保存筛选</span>
              </el-checkbox>
              <InfoIcon content="仅保存默认筛选内容，刷新页面后须点击[确定]执行筛选操作"/>
            </div>
            <div v-if="hasRouteAuth('chart:departEdit:config')" class="button-text" @click="setConfigFilter">筛选项配置</div>
          </div>
        </div>
        <template v-if="filterList.length">
          <div v-for="(item, index) in filterList" :key="index" class="filter-item">
            <ToolTip :content="handelFiedlName(item.field)" class="label" />
            <div class="input">
              <el-date-picker
                v-if="isTimeField(item)"
                v-model="paramsObj[item.field]"
                :picker-options="pickerOptions"
                :append-to-body="appendToBody"
                :editable="false"
                :default-time="['00:00:00', '23:59:59']"
                clearable
                size="small"
                type="datetimerange"
                format="yyyy/MM/dd HH:mm"
                value-format="timestamp"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeData"/>
              <selectDept v-else-if="isDeptField(item)" v-model="paramsObj[item.field]" link-children class="dept-select" @changeValue="changeData" />
              <el-number-range
                v-else-if="isNumberField(item)"
                v-model="paramsObj[item.field]"
                :max="100000000"
                :min="-10000000"
                class="number-range"
                start-placeholder="开始"
                end-placeholder="结束"
                clearable
                @onChange="changeData"
              />
              <!-- <el-autocomplete
                v-else
                v-model="paramsObj[item.field]"
                :fetch-suggestions="(queryString, cb) => {querySearch(queryString, cb, item)}"
                :placeholder="item.field"
                size="small"
                clearable
                @change="changeData"
              /> -->
              <el-input v-else v-model="paramsObj[item.field]" placeholder="请输入" clearable size="small" type="text" @change="changeData" />
            </div>
          </div>
        </template>
        <EmptyPlaceholder v-else :empty-img-top="'0'" :is-border="false" :text="emptyText" :show-img="false" text-color="#999" class="empty-tip" />
        <slot />
        <div v-if="filterList.length || (mode === 'single' && !hideBtn)" class="btn-container">
          <el-button size="small" type="primary" @click="submit">确定</el-button>
        </div>

      </div>
      <div v-if="mode === 'single'" slot="reference" :class="{'block':popperShow}" class="filter-img">
        <el-image :src="FilterBtnIcon"/>
      </div>
      <div v-else slot="reference">
        <slot v-if="isBtn" name="btnReference" />
        <div v-else :title="tipText" class="action-btn-box">
          <el-tooltip content="全局筛选" placement="left">
            <img :src="FilterIcon" style="width: 16px; height: 16px" alt="全局筛选">
          </el-tooltip>
        </div>
      </div>
    </el-popover>
    <FilterDialog v-if="mode!=='single'" ref="filterDialogRef" :tab-id="tabId" @freshData="freshData" />
  </div>
</template>

<script>
// api
// setGlobalFilter
import { getGlobalFilter } from '@/api/reportManage';
// components
import selectDept from '@/components/Common/baseComponent/selectDept';
import Title from '@/components/Title';
import toolMethods from '@/components/ReportManage/dataFilter/mixins/toolMethods';
import elNumberRange from '@/components/Tool/module/numberRange';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import FilterDialog from './setFilterDialog';
import { hasRouteAuth } from '@/utils/permission';

// img
import FilterIcon from '@/assets/chartsTheme/adsorbButton/filter-icon.png';
import FilterBtnIcon from '@/assets/chartsTheme/filter_btn.png';
export default {
  components: { Title, selectDept, elNumberRange, EmptyPlaceholder, FilterDialog },
  mixins: [toolMethods],
  model: {
    prop: 'paramsObj',
    event: 'changeValue'
  },
  props: {
    paramsObj: {
      type: Object,
      default: () => {
        return {};
      }
    },
    insertFilterList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    emptyText: {
      type: String,
      default: '暂无筛选项'
    },
    title: {
      type: String,
      default: '全局筛选'
    },
    right: {
      type: Number,
      default: 80
    },
    mode: {
      type: String,
      default: ''
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
    init: {
      type: Boolean,
      default: false
    },
    getFilterList: {
      type: Function,
      default: null
    },
    tabId: {
      type: String | Number,
      default: ''
    },
    hideBtn: {
      type: Boolean,
      default: false
    },
    isBtn: {
      type: Boolean,
      default: false
    },
    isGlobal: { // 是否全局筛选
      type: Boolean,
      default: false
    },
    tipText: { // 全屏状态下tool-tip失效
      type: String,
      default: ''
    }
  },
  data() {
    return {
      FilterBtnIcon,
      FilterIcon,
      saveFilter: true,
      globalFilterList: [],
      popperShow: false,
      popperOptions: {
        boundariesElement: '#fullarea'
      },
      pickerOptions: {
        shortcuts: [{
          text: '今日',
          onClick(picker) {
            const begin = new Date(new Date().setHours(0, 0, 0, 0));
            const end = new Date(new Date().setHours(0, 0, 0, 0) + (24 * 60 * 60 * 1000 - 1));
            picker.$emit('pick', [begin, end]);
          }
        }, {
          text: '昨日',
          onClick(picker) {
            const begin = new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000);
            const end = new Date(new Date().setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [begin, end]);
          }
        }, {
          text: '本周',
          onClick(picker) {
            const now = new Date();
            const nowTime = now.setHours(0, 0, 0, 0);
            const day = now.getDay();
            const oneDayTime = 24 * 60 * 60 * 1000;
            const MondayTime = nowTime - (day - 1) * oneDayTime;// 显示周一
            const SundayTime = (nowTime + oneDayTime - 1) + (7 - day) * oneDayTime;// 显示周日
            picker.$emit('pick', [new Date(MondayTime), new Date(SundayTime)]);
          }
        }, {
          text: '上周',
          onClick(picker) {
            const now = new Date();
            const nowTime = now.setHours(0, 0, 0, 0);
            const day = now.getDay();
            const oneDayTime = 24 * 60 * 60 * 1000;
            const MondayTime = nowTime - (day + (7 - 1 - 0)) * oneDayTime;// 显示上周一
            const SundayTime = (nowTime + oneDayTime - 1) - (day + (7 - 1 - 6)) * oneDayTime;// 显示上周日
            picker.$emit('pick', [new Date(MondayTime), new Date(SundayTime)]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const start = new Date(year, month, 1, 0, 0, 0);
            const end = new Date(new Date(year, month + 1, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '上月',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth();
            const start = new Date(year, month - 1, 1, 0, 0, 0);
            const end = new Date(new Date(year, month, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本年',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear();
            const start = new Date(year, 0, 1, 0, 0, 0);
            const end = new Date(new Date(year + 1, 0, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '去年',
          onClick(picker) {
            const now = new Date();
            const year = now.getFullYear() - 1;
            const start = new Date(year, 0, 1, 0, 0, 0);
            const end = new Date(new Date(year + 1, 0, 1).setHours(0, 0, 0, 0) - 1);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    };
  },
  computed: {
    filterList: {
      get() {
        if (this.mode === 'single') {
          return this.insertFilterList;
        } else {
          return this.globalFilterList;
        }
      }
    }
  },
  created() {
    if (this.mode === 'single' && !this.init) {
      const list = this.insertFilterList;
      if (list && list.length) {
        this.initData(list);
      }
    } else if (this.tabId && !this.init) {
      this.getFilter(true);
    }
  },
  methods: {
    hasRouteAuth,
    freshData(filterList) {
      if (filterList) {
        this.emptyData(this.paramsObj);
        this.globalFilterList = filterList;
        this.initData(this.globalFilterList);
      } else {
        this.getFilter(true);
      }
    },
    /**
     * 获取全局筛选配置列表
     * @param {Object} reset - 是否重置参数
     * @param {Object} tabId - tabId，不传则默认使用 this.tabId
     * @param {Object} insertCache - 重置参数时，是否注入缓存
     */
    getFilter(reset = false, tabId = null, insertCache = false) {
      const params = {
        tabId: tabId || this.tabId
      };
      if (reset) this.emptyData(this.paramsObj, insertCache, params.tabId);
      getGlobalFilter(params).then(res => {
        this.globalFilterList = (res && res.data) || [];
        const paramsCache = localStorage.getItem(`globalFilterParams${tabId || this.tabId}`);

        if (!insertCache || !paramsCache) {
          this.initData(this.globalFilterList);
        }
        this.$emit('changeValue', this.paramsObj);
      });
    },
    emptyData(params, insertCache = false, tabId = null) {
      if (params) {
        for (const key in params) {
          delete params[key];
        }
      }
      this.$emit('changeValue', {});
      if (insertCache) {
        const paramsCache = localStorage.getItem(`globalFilterParams${tabId || this.tabId}`);
        if (paramsCache) {
          this.$emit('changeValue', this.jsonParse(paramsCache));
        }
      }
    },
    initData(filter) {
      //  0:文本型 1:  时间日期  2: 数值型   3: 部门
      filter.forEach(i => {
        if (this.isTimeField(i)) {
          i.$fieldType = 1;
          if (!this.paramsObj[i.field]) {
            if (i.defaultMath) {
              i.defaultTimeRange = this.getTime(i.defaultMath);
            }
            this.$set(this.paramsObj, i.field, i.defaultTimeRange || []);
          }
        } else if (this.isNumberField(i)) {
          i.$fieldType = 2;
          if (!this.paramsObj[i.field]) this.$set(this.paramsObj, i.field, i.defaultNumberRange || []);
        } else if (this.isDeptField(i)) {
          i.$fieldType = 3;
          if (!this.paramsObj[i.field]) this.$set(this.paramsObj, i.field, i.defaultValue || '');
        } else {
          i.$fieldType = 0;
          if (!this.paramsObj[i.field]) this.$set(this.paramsObj, i.field, i.defaultValue || '');
        }
      });
    },
    getTime(defaultMath) {
      const switchObj = {
        'day': () => { // 今日
          const begin = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
          const end = new Date(new Date().setHours(0, 0, 0, 0) + (24 * 60 * 60 * 1000 - 1)).getTime();
          return [begin, end];
        },
        'yesterday': () => { // 昨日
          const begin = new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000).getTime();
          const end = new Date(new Date().setHours(0, 0, 0, 0) - 1).getTime();
          return [begin, end];
        },
        'week': () => { // 本周
          const now = new Date();
          const nowTime = now.setHours(0, 0, 0, 0);
          const day = now.getDay();
          const oneDayTime = 24 * 60 * 60 * 1000;
          const MondayTime = nowTime - (day - 1) * oneDayTime;// 显示周一
          const SundayTime = (nowTime + oneDayTime - 1) + (7 - day) * oneDayTime;// 显示周日
          return [new Date(MondayTime).getTime(), new Date(SundayTime).getTime()];
        },
        'lastweek': () => { // 上周
          const now = new Date();
          const nowTime = now.setHours(0, 0, 0, 0);
          const day = now.getDay();
          const oneDayTime = 24 * 60 * 60 * 1000;
          const MondayTime = nowTime - (day + (7 - 1 - 0)) * oneDayTime;// 显示上周一
          const SundayTime = (nowTime + oneDayTime - 1) - (day + (7 - 1 - 6)) * oneDayTime;// 显示上周日
          return [new Date(MondayTime).getTime(), new Date(SundayTime).getTime()];
        },
        'month': () => { // 本月
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const start = new Date(year, month, 1, 0, 0, 0).getTime();
          const end = new Date(new Date(year, month + 1, 1).setHours(0, 0, 0, 0) - 1).getTime();
          return [start, end];
        },
        'lastmonth': () => { // 上月
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const start = new Date(year, month - 1, 1, 0, 0, 0).getTime();
          const end = new Date(new Date(year, month, 1).setHours(0, 0, 0, 0) - 1).getTime();
          return [start, end];
        },
        'year': () => { // 本年
          const now = new Date();
          const year = now.getFullYear();
          const start = new Date(year, 0, 1, 0, 0, 0).getTime();
          const end = new Date(new Date(year + 1, 0, 1).setHours(0, 0, 0, 0) - 1).getTime();
          return [start, end];
        },
        'lastyear': () => { // 去年
          const now = new Date();
          const year = now.getFullYear() - 1;
          const start = new Date(year, 0, 1, 0, 0, 0).getTime();
          const end = new Date(new Date(year + 1, 0, 1).setHours(0, 0, 0, 0) - 1).getTime();
          return [start, end];
        },
        '30days': () => { // 近30日
          // 30天前的凌晨
          const begin = new Date(new Date().setHours(0, 0, 0, 0)).getTime() - (29 * 24 * 60 * 60 * 1000);
          const end = new Date(new Date().setHours(0, 0, 0, 0) + (24 * 60 * 60 * 1000 - 1)).getTime();
          return [begin, end];
        }
      };
      const time = switchObj[defaultMath] && switchObj[defaultMath]();
      return time || [];
    },
    /**
     * 事件
     */
    querySearch(queryString, cb, item) {
      cb(item.defaultSelect || []);
    },
    changeData() {
      // this.$emit('handelAllChange', this.paramsObj);
    },
    submit() {
      this.paramsObj.isGlobal = this.isGlobal;
      this.$emit('changeValue', this.paramsObj);
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      if (this.mode !== 'single') {
        if (this.saveFilter) {
          localStorage.setItem(`globalFilterParams${this.tabId}`, JSON.stringify(this.paramsObj));
        } else {
          localStorage.removeItem(`globalFilterParams${this.tabId}`);
        }
      }
      this.$emit('handelAllChange', params);
      this.popperShow = false;
    },
    show() {
      this.$emit('show');
    },
    setConfigFilter() {
      this.popperShow = false;
      this.$refs.filterDialogRef && this.$refs.filterDialogRef.openDialog(this.filterList);
    },
    jsonParse(data) {
      try {
        return JSON.parse(data);
      } catch (error) {
        return {};
      }
    },
    handelFiedlName(fieldName) {
      if (fieldName && fieldName.indexOf('#') >= 0) {
        return fieldName.split('#')[0];
      }
      return fieldName;
    }
  }
};
</script>

<style lang="scss" scoped>
.filter-list {
  min-width: 300px;
  .filter-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .label {
      font-size: 14px;
      color: #999;
      margin-right: 10px;
      width: 70px;
      text-align: right;
      ::v-deep .ellipsisOne {
        text-align: right;
        width: 100%;
      }
    }
    .input {
      width: 240px;
      &::v-deep {
        .el-input {
          width: 240px;
        }
        .el-date-editor {
          width: 240px;
        }
        .el-tag.el-tag--info {
          color: #406eff !important;
          background: #eff3fb;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
  .empty-tip {
    width:250px;
    margin: 0 auto;
    text-align:center;
  }
  .btn-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
.top-container {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
  .top-btn {
    display: flex;
    align-items: center;
    margin-left: 10px;
    z-index: 10;
  }
  .flex {
    flex:1;
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.action-btn-box {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  &:hover {
    background-color: #2D58E2;
  }
}
.opacity {
  opacity: 1;
}
.filter-img {
  height: 20px;
  width: 20px;
  display: none;
  >img {
    width: 100%;
    height: 100%;
  }
  cursor: pointer;
}

.block {
  display: block !important;
}
</style>

